from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from MarketApp.models import AxfFoodType, AxfGoods
from MarketApp.view_constant import COMP_SORT_RULE, ORDER_BY_PRICE_UP, ORDER_BY_PRICE_DOWN, ORDER_BY_PRODUCTNUM_UP, \
    ORDER_BY_PRODUCTNUM_DOWN

def market(request):
    foodtypes = AxfFoodType.objects.all()

    typeid = request.GET.get('typeid', '104749')  # 默认值为'104749'字符串，即刚进入闪购页面的时候展示该查询结果

    # childtypenames = AxfFoodType.objects.filter(typeid=typeid)
    # print(childtypenames) < QuerySet[ < AxfFoodType: AxfFoodType object >] >

    childtypenames = AxfFoodType.objects.filter(typeid=typeid)[0].childtypenames  # ...[0] 表示第一个对象
    # print(childtypenames) 全部分类: 0  # 酸奶乳酸菌:103537#牛奶豆浆:103538#面包蛋糕:103540

    childtype_list = childtypenames.split('#')
    # print(childtype_list)  ['全部分类:0', '酸奶乳酸菌:103537', '牛奶豆浆:103538', '面包蛋糕:103540']

    c_list = []

    for childtypename in childtype_list:
        # ['酸奶乳酸菌', '103537']
        c = childtypename.split(':')
        c_list.append(c)
    # print(c_list)  [['全部分类', '0'], ['酸奶乳酸菌', '103537'], ['牛奶豆浆', '103538'], ['面包蛋糕', '103540']]

    # axfoodtyped的typeid == axfgoods的categoryid
    goods_list = AxfGoods.objects.filter(categoryid=typeid)

    childcid = request.GET.get('childcid', '0')

    # 如果是第一次跳转到这个视图函数，那么就没有childcid的，所有查询的是所有
    if childcid == '0':
        goods_list = goods_list
    else:
        goods_list = goods_list.filter(childcid=childcid)

    # 综合排序
    sort_rule_list = [
        ['综合排序', COMP_SORT_RULE],
        ['价格升序', ORDER_BY_PRICE_UP],
        ['价格降序', ORDER_BY_PRICE_DOWN],
        ['销量升序', ORDER_BY_PRODUCTNUM_UP],
        ['销量降序', ORDER_BY_PRODUCTNUM_DOWN],
    ]

    s_rule = request.GET.get('s_rule', '0')

    if s_rule == COMP_SORT_RULE:
        pass
    elif s_rule == ORDER_BY_PRICE_UP:
        goods_list = goods_list.order_by('price')
    elif s_rule == ORDER_BY_PRICE_DOWN:
        goods_list = goods_list.order_by('-price')
    elif s_rule == ORDER_BY_PRODUCTNUM_UP:
        goods_list = goods_list.order_by('productnum')
    elif s_rule == ORDER_BY_PRODUCTNUM_DOWN:
        goods_list = goods_list.order_by('-productnum')

    context = {
        'foodtypes': foodtypes,
        'goods_list': goods_list,
        'typeid': typeid,
        'c_lists': c_list,
        'chilecid': childcid,
        'sort_rule_list': sort_rule_list,
        's_rule': s_rule
    }
    return render(request, 'AXF/main/market/market.html', context=context)
